﻿using Microsoft.AspNetCore.Mvc;
using MyMES.IServices.MaterialCatalogs;
using System.Threading.Tasks;
using System;
using VOL.Entity.DomainModels;

[Route("api/[controller]/[action]")]
[ApiController]
public class MaterialCatalogsController : ControllerBase
{
    private readonly IMaterialCatalogService _materialCatalogService;

    public MaterialCatalogsController(IMaterialCatalogService materialCatalogService)
    {
        _materialCatalogService = materialCatalogService;
    }

    /// <summary>
    /// 获取分类树
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetTree()
    {
        var tree = await _materialCatalogService.GetMaterialCatalogTreeAsync();
        return Ok(tree);
    }

    /// <summary>
    /// 新增分类
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> Add([FromBody] MaterialCatalog entity)
    {
        try
        {
            var result = await _materialCatalogService.AddAsync(entity);
            return Ok(new { success = result, message = "添加成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 修改分类
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> Update([FromBody] MaterialCatalog entity)
    {
        try
        {
            var result = await _materialCatalogService.UpdateAsync(entity);
            return Ok(new { success = result, message = "修改成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 删除分类
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> Delete([FromBody] MaterialCatalog model)
    {
        try
        {
            var result = await _materialCatalogService.DeleteAsync(model.Id);
            return Ok(new { success = result, message = "删除成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
    }
}